package StudyCode.summary.Basic.mystring;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class StringNumber {
	public static void main(String[] args) {

		String text = "0.1";
		String text1 = "0.1A";

		System.out.println("方法1：");
		System.out.println(method1IsNumber(text));
		System.out.println(method1IsNumber(text1));

		System.out.println("方法2：");
		System.out.println(method2IsNumber(text));
		System.out.println(method2IsNumber(text1));
	}

	private static boolean method1IsNumber(String text) {
		try {
			Double.valueOf(text);
		} catch (Exception ex) {
			return false;
		}
		return true;
	}

	private static boolean method2IsNumber(String text) {
		return isWholeNumber(text) || isDecimal(text);
	}

	/**
	 * 判断是否全为数字
	 */
	public static boolean isWholeNumber(String orginal) {
		return isMatch("^[+-]?0$", orginal) || isPositiveInteger(orginal) || isNegativeInteger(orginal);
	}

	/**
	 * 判断是否全为整数
	 */
	public static boolean isInteger(String orginal) {
		return isPositiveInteger(orginal) || isNegativeInteger(orginal);
	}

	/**
	 * 判断是否为正整数
	 */
	public static boolean isPositiveInteger(String orginal) {
		return isMatch("^\\+?[1-9]\\d*$", orginal);
	}

	/**
	 * 判断是否为负整数
	 */
	public static boolean isNegativeInteger(String orginal) {
		return isMatch("^-[1-9]\\d*$", orginal);
	}

	/**
	 * 判断是否为正浮点数
	 */
	public static boolean isPositiveDecimal(String orginal) {
		return isMatch("^\\+?[0]\\.[1-9]*$|^\\+?[1-9]\\d*\\.\\d*$", orginal);
	}

	/**
	 * 判断是否为负浮点数
	 */
	public static boolean isNegativeDecimal(String orginal) {
		return isMatch("^-[0]\\.[1-9]*$|^-[1-9]\\d*\\.\\d*$", orginal);
	}

	/**
	 * 判断是否为浮点数
	 */
	public static boolean isDecimal(String orginal) {
		return isMatch("^[-+]?\\d+\\.\\d*$|^[-+]?\\d*\\.\\d+$", orginal);
	}

	public static boolean isMatch(String regex, String orginal) {
		if (orginal == null || orginal.trim().equals("")) {
			return false;
		}
		Pattern pattern = Pattern.compile(regex);
		Matcher matcher = pattern.matcher(orginal);
		return matcher.matches();
	}
}
